#include "rock.h"

#include <QPainter>
#include <QDebug>
#include <QGraphicsScene>

Rock::Rock(Hole* hole, qreal w, qreal h, QGraphicsItem *parent)
    : hole_(hole)
    , w_(w)
    , h_(h)
    , QGraphicsItem(parent)
{
    hole->setHasRock(true);
    setFlag(ItemIsMovable, true);
    //setFlag(ItemSendsScenePositionChanges, true);
}

QRectF Rock::boundingRect() const {
    return QRectF(0, 0, w_, h_);
}

QPainterPath Rock::shape() const
 {
     QPainterPath path;
     path.addEllipse(boundingRect());
     return path;
 }

void Rock::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    painter->setBrush(Qt::green);
    painter->drawEllipse(boundingRect());
}

void Rock::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    setZValue(1);
    position_ = pos();
    qDebug() << position_;
}

void Rock::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
    setZValue(0);

    QList<QGraphicsItem *> items = collidingItems();

    Hole* newHole = 0;
    for (auto i = items.begin(); i != items.end(); ++i) {
        newHole = qgraphicsitem_cast<Hole *>(*i);
        if (newHole != 0) {
            break;
        }
    }

    if (newHole) {
        qDebug() << "New hole: " << newHole->row() << " " << newHole->col();
        qDebug() << "Old hole: " << hole_->row() << " " << hole_->col();
        if (newHole->hasRock() || !hole_->availableNextHole(newHole)) {
            qDebug() << "Has rock: " << newHole->hasRock();
            qDebug() << "availableNextHole: " << hole_->availableNextHole(newHole);
            setPos(position_);
        } else {
            hole_->setHasRock(false);
            setPos(newHole->rockX() - w_ / 2, newHole->rockY() - h_ / 2);

            int rowDelete = (newHole->row() + hole_->row()) / 2;
            int colDelete = (newHole->col() + hole_->col()) / 2;
            hole_->getBoard()->removeRock(rowDelete, colDelete);

            hole_ = newHole;
            newHole->setHasRock(true);
        }
    } else {
        setPos(position_);
    }

    QGraphicsItem::mouseReleaseEvent(event);
}
